package SingletonPattern;

import java.util.HashMap;
import java.util.Map;

// Singleton Pattern
public class DatabaseConnection {
    private static DatabaseConnection instance;
    private final Map<Integer, String> books;

    private DatabaseConnection() {
        //Initializing database connection
        books = new HashMap<>();
        System.out.println("Database connection initialized.");
    }

    public static synchronized DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }

    public void addBook(int id, String title) {
        //Adding a book to the database
        books.put(id, title);
        System.out.println("Model.Book added: " + title);
    }

    public String getBook(int id) {
        //Retrieving a book from the database
        String title = books.get(id);
        System.out.println("Retrieved book: " + title);
        return title;
    }

    public void removeBook(int id) {
        //Removing a book from the database
        String title = books.remove(id);
        System.out.println("Model.Book removed: " + title);
    }

    public String searchBook(String title) {
        //Searching for a book in the database based on book title
        for (Map.Entry<Integer, String> entry : books.entrySet()) {
            if (entry.getValue().toLowerCase().contains(title.toLowerCase())) {
                System.out.println("Found book: " + entry.getValue());
                return entry.getValue();
            }
        }
        System.out.println("Model.Book not found for title: " + title);
        return null;
    }

    public void closeConnection() {
        //Closing database connection
        System.out.println("Database connection closed.");
        // Logic for closing connection
    }
}
